var mongoose =require('mongoose');
var User = require('../models/comments-modules');

//新增数据
exports.create = function(req,res,next){
    var user = new User(req.body);
    user.save()
    .then(data=>{
        console.log(data);
        res.json(data);
    })
}

//修改
exports.update = function(req,res,next){
    
      var id = req.params.id; // req.param('id')
      // 现在操作的都是mongoose而不是mongodb
      User.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
      .then(data=>{
          res.json({msg:'数据修改成功',status:200}); // 如果你要返回数据，这个data返回的是你之前修改的那个数据内容
      })
  }
  
  //删除
    exports.remove = function(req,res,next){
        var id = req.params.id;   //此时id是传过来的值
        id = id.split(',');   //将传递的id值变成数组遍历
            console.log(typeof id);
        let leng = id.length;
        for(var i=0;i<leng;i++){
            User.findByIdAndRemove(id[i],function(err,doc){
                if(err){
                    console.log("数据删除异常"+err);
                    return;
                }else{
                    res.json({msg:'数据删除成功',status:200})
                }
            })
        }
    } 

 //查找
 exports.list = function(req,res,next){
    console.log(req);
    var page = (req.body.page) ? req.body.page : 1;
    var rows = (req.body.rows) ? req.body.rows : 10;
    rows = parseInt(rows);
    var queryCondition = {};
    var name;
    if( req.body.name && req.body.name.trim().length>0 ){
        name = req.body.name;
        queryCondition = {"name":new RegExp(name,'i')};
    }

    if(req.body.newsID && req.body.newsID.trim().length>0){
        newsID=req.body.newsID;
        queryCondition={
            "newsID":newsID
        }
    }


    // News.paginate(queryCondition,{page:page,limit:rows},(err,result)=>{
    //     //实现动态显示条数
    //     result.rows = result.docs;
    //     delete result.docs;
    //     res.json(result);
    // })

    //对查找到的数据进行分页
    User.paginate(queryCondition, { page: page, limit: rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
       res.json(result)
    });
}

    //查找对应文章id的值
    exports.listtoo = function(req,res,next){
        var id = req.params.id; // req.param('id')
        var query = {blogsid:id}
        User.find(query,(err,result) => {
            res.json(result)
        })
    }